package com.ktjiaoyu.service.impl;

import com.ktjiaoyu.service.UploadService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile; // 引入 Spring 文件上传类

import java.io.File;
import java.lang.invoke.MutableCallSite;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service("toLocalUploadServiceImpl")
public class ToLocalUploadServiceImpl implements UploadService {
    private static final Logger logger = LoggerFactory.getLogger(ToLocalUploadServiceImpl.class);

    public static final String UPLOAD_PATH = "/static/upload/";

    @Resource
    private HttpServletRequest request; // 注入 request 主要用于获取本地路径

    @Override
    public String uploadFile(MultipartFile uploadFile, String... allowFileExtends) throws Exception {
        Set<String> include = new HashSet<>(Arrays.asList(allowFileExtends));
        // 获取文件保存路径（服务器本地路径）
        String rootPath = request.getServletContext().getRealPath(UPLOAD_PATH);

        // 检查上传的文件是否为空
        if (!uploadFile.isEmpty()) {
            String fileName=uploadFile.getOriginalFilename();
            //获取上传文件的扩展名
            String extension= StringUtils.getFilenameExtension(fileName);
            //如果不包括扩展名
            if (!include.contains(extension)){
                throw new Exception("上传文件仅支持"+include+"扩展名");
            }
            String uploadFileName= UUID.randomUUID()+"."+extension;
            File file=new File(rootPath,uploadFileName);
            //父目录不存在是无法保存的
            if (!file.getParentFile().exists()){
                //创建父目录
                file.getParentFile().mkdirs();
            }
            try{
                //将上传的文件保存到本地路径
                uploadFile.transferTo(file);
                //返回文件路径
                return UPLOAD_PATH+uploadFileName;
            }catch (Exception e){
                logger.error("上传文件失败",e);
                throw e;
            }
        }
        return null;
    }
}